package espacokidsadm.web.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/*@FacesConverter("CpfConverter")*/
@FacesConverter(forClass=CpfCnpjConverter.class)
public class CpfCnpjConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
		if(value != null && value.trim().length() > 0){
			String cpfCnpj = value.replaceAll("\\.","").replaceAll("\\-","");
			try{
				//testa se somente números
				Long.valueOf(cpfCnpj);
				return cpfCnpj;
			}catch(NumberFormatException e){
				FacesMessage message = new FacesMessage();
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				message.setDetail("Não foi possível converter o valor para um cpfCnpj");
				throw new ConverterException(message);
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if(value != null){
			String cpfCnpj = value.toString();
			if(cpfCnpj.length() > 11){
				cpfCnpj = cpfCnpj.substring(0, 2) + "." + 
						  cpfCnpj.substring(2, 5) + "." + 
						  cpfCnpj.substring(5, 8) + "/" + 
						  cpfCnpj.substring(8, 12) + "-" + 
						  cpfCnpj.substring(12);
			}else{
				cpfCnpj = cpfCnpj.substring(0, 3) + "." + 
						  cpfCnpj.substring(3, 6) + "." + 
						  cpfCnpj.substring(6, 9) + "-" + 
						  cpfCnpj.substring(9);
			}
			return cpfCnpj;
		}else
			return null;
	}

}
